/**
 * Copyright 2021 xpstem.com
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.xpstem.lelink.type;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Objects;

/**
 * Zero terminated string
 *
 * @author billy zhang
 */
public class DataS implements EV3Type  {

    public static final short ZERO_TERMINATED = 0x00;

    private int length;
    private String value;

    public DataS(int length) {
        this.length = length;
    }

    private DataS(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    public static DataS from(String value) {
        return new DataS(value);
    }

    public void writeTo(OutputStream outStream) throws IOException {
        outStream.write(value.getBytes());
        outStream.write(ZERO_TERMINATED);
    }

    @Override
    public int size() {
        return length;
    }

    @Override
    public EV3Type copy() {
        return new DataS(value);
    }

    @Override
    public void readFrom(InputStream inStream, int index) throws IOException {
        inStream.skip(index);
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        int data;
        while ((data=inStream.read()) != 0x00) {
            outStream.write(data);
        }
        value = new String(outStream.toByteArray());
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) { return true; }
        if (o == null || getClass() != o.getClass()) { return false; }
        DataS data = (DataS) o;
        return value.equals(data.value);
    }

    @Override
    public int hashCode() {
        return Objects.hash(value);
    }

}
